package com.ebc.eservice.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ebc.eservice.mapper.*;
import com.ebc.eservice.pojo.*;
import com.ebc.eservice.service.EbcCardService;
import com.ebc.eservice.util.CurrentUser;
import com.ebc.eservice.util.JsonResult;
import com.ebc.eservice.util.excel.DownloadExcel;
import com.ebc.eservice.vo.card.Manage.CardStatDTO;
import com.ebc.eservice.vo.card.Manage.staffClientDTO;
import com.ebc.eservice.vo.card.staff.CardInfoReqVo;
import com.ebc.eservice.vo.card.Manage.StaffStatListVo;
import com.ebc.eservice.vo.card.staff.UpdateStaffInfoReqVo;
import com.ebc.eservice.vo.excel.StaffExportExcel;
import com.ebc.eservice.vo.sector.SectorByChildDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: Joey
 * @Description:名片实现类 员工的实现操作
 * @date:2022/9/19 10:10
 */
@Service
public class CardImp implements EbcCardService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private CardMapper cardMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private CompanySectorMapper companySectorMapper;
    @Autowired
    private RoleMapper roleMapper;



    //添加员工
    @Override
    @Transactional(rollbackFor=Exception.class)
    public JsonResult addPeronCard(CardInfoReqVo cReqVo) {
        if(getRoleByUserId(cReqVo.getUserId()) == 1){//查询账号是否是员工账户

            CurrentUser currentUser = new CurrentUser();
            //查询子级部门信息
            SectorByChildDto childDto = companySectorMapper.SectorInfoByChildId(cReqVo.getSectorId());
            EbcCard card = new EbcCard();
            card.setUserId(cReqVo.getUserId())
                    .setPosition("客户经理-"+cReqVo.getUserId())
                    .setDel(0)
                    .setCompanyId(cReqVo.getCompanyId())
                    .setCreateId(currentUser.getCurrentEbcUser().getId())//创建人id
                    .setSectorId(childDto.getSectorId())//父级部门
                    .setSectorChildId(childDto.getChildId());//子级部门
            int insert = cardMapper.insert(card);

            if(insert>0){
                EbcUser user = userMapper.selectById(cReqVo.getUserId());
                user.setEmail(cReqVo.getEmail()).setWechat(cReqVo.getWxAccount());
                userMapper.updateById(user);
                return JsonResult.success("员工添加成功");
            }
        }
        return JsonResult.fail("添加失败,请求异常");
    }


    //获取员工列表
    @Override
    public JsonResult getStaffList(int current ,int size, Integer companyId) {
        Page<StaffStatListVo> page = new Page<>(current,size,false);
        IPage<StaffStatListVo> staffList = userMapper.getStaffList(page, companyId);
        List<StaffStatListVo> staffListRecords = staffList.getRecords();

        List<Integer> list = new ArrayList<>();
        //客户数量
        for (StaffStatListVo record : staffListRecords) {
            List<staffClientDTO> clientNum = record.getClientNum();
            if(clientNum == null){
                list.add(0);
            }else{
                for (staffClientDTO clientDTO : clientNum) {
                    list.add(clientDTO.getClientNum());
                }
            }
        }
        //排序flag
        List<StaffStatListVo> std = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            StaffStatListVo vo = staffListRecords.get(i);
            vo.setFlag(list.get(i));
            std.add(vo);
        }
        //排序后的列表
        std.sort(Comparator.comparing(StaffStatListVo::getFlag).reversed());
        return JsonResult.success(std);
    }

    //top3
    @Override
    public JsonResult getTopThreeList(Integer companyId) {
        Page<StaffStatListVo> page = new Page<>(1,100,false);
        IPage<StaffStatListVo> staffList = userMapper.getStaffList(page, companyId);
        List<StaffStatListVo> staffListRecords = staffList.getRecords();

        List<Integer> list = new ArrayList<>();
        for (StaffStatListVo record : staffListRecords) {
            List<staffClientDTO> clientNum = record.getClientNum();
            if(clientNum == null){
                list.add(0);
            }else{
                for (staffClientDTO clientDTO : clientNum) {
                    list.add(clientDTO.getClientNum());
                }
            }
        }
        List<StaffStatListVo> std = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            StaffStatListVo vo = staffListRecords.get(i);
            vo.setFlag(list.get(i));
            std.add(vo);
        }

        std.sort(Comparator.comparing(StaffStatListVo::getFlag).reversed());
        List<StaffStatListVo> topList = null;
        if(std.size()>0){
            topList = std.subList(0,3);
        }

        return JsonResult.success(topList);
    }


    //编辑员工信息
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult updateStaffInfo(UpdateStaffInfoReqVo modifyStaff) {
        //获取父级部门
        SectorByChildDto childDto = companySectorMapper.SectorInfoByChildId(modifyStaff.getSectorId());
        //员工账户信息
        EbcUser ebcUser = userMapper.selectById(modifyStaff.getUserId());
        ebcUser.setEmail(modifyStaff.getEmail()).setWechat(modifyStaff.getWxAccount());
        userMapper.updateById(ebcUser);
        //员工名片信息
        EbcCard ebcCard = cardMapper.selectById(modifyStaff.getCardId());
        ebcCard.setPosition(modifyStaff.getPosition())
                .setSectorId(childDto.getSectorId()).setSectorChildId(childDto.getChildId());
        cardMapper.updateById(ebcCard);

        return JsonResult.success("修改成功,card:"+ebcCard.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult deleteStaff(Integer cardId) {
        cardMapper.deleteById(cardId);
        return JsonResult.success("删除成功, cardId: "+cardId);
    }

    //todo 获取的企业列表 需要修改
    @Override
    public JsonResult getCompanyList() {
        List<EbcCompany> companies = companyMapper.selectList(null);
        return JsonResult.success(companies);
    }


    //todo 筛选部门
    @Override
    public JsonResult getSectorByCompany(Integer cid) {

        List<EbcCompanySector> selectList = companySectorMapper.selectList(Wrappers.<EbcCompanySector>lambdaQuery()
                .and(wrapper -> wrapper.eq(EbcCompanySector::getCompanyId, cid)));
        return JsonResult.success(selectList);
    }

    public int getRoleByUserId(Integer uid){
        List<EbcRole> user = roleMapper.getUserRolesByUid(uid);
        int gg = user.get(0).getId();
        if(gg == 1){
            return 1;
        }
        return 0;
    }


    //导出excel 员工信息表
    @Override
    public void exportStaffExcel(HttpServletResponse response, Integer companyId) throws IllegalAccessException, IOException, InstantiationException {
        Page<StaffStatListVo> page = new Page<>(1,100,false);
        IPage<StaffStatListVo> staffList = userMapper.getStaffList(page, companyId);
        List<StaffStatListVo> staffListRecords = staffList.getRecords();

        StaffExportExcel seex = null;
        List<StaffExportExcel> list = new ArrayList<>();
        for (StaffStatListVo record : staffListRecords) {
            seex = new StaffExportExcel();
            seex.setCardid(record.getCardId()).setStaffid(record.getStaffId())
            .setStaffname(record.getStaffName()).setStaffposition(record.getStaffPosition())
                    .setSectorname(record.getSectorName()+"-"+record.getSectorChildName())
            .setCreatetime(record.getCreateTime()).setCreator(record.getCreator());

            List<staffClientDTO> clientNum = record.getClientNum();
            List<CardStatDTO> cardStatDTO = record.getCardStatDTO();

            for (staffClientDTO clientDTO : clientNum) {
                if(clientDTO==null){
                    break;
                }
                seex.setClientnum(clientDTO.getClientNum());
            }
            for (CardStatDTO statDTO : cardStatDTO) {
                if(statDTO ==null){
                    break;
                }
                seex.setVisitnum(statDTO.getVisitNum()).setActivenum(statDTO.getActiveNum())
                .setMessagenum(statDTO.getMessageNum()).setSavecardnum(statDTO.getSaveCardNum())
                .setAddcontactnum(statDTO.getAddContactNum()).setStaytimes(statDTO.getStayTimes());
            }
            list.add(seex);
        }

        DownloadExcel.downloadStaff(response,StaffExportExcel.class,list,companyId);


    }
}
